Centos7一键加固脚本

脚本使用

1
sh ./init_centos7.sh

init_centos7.sh 脚本如下,请直接粘贴到linux 文本编辑器中,使用window 文本编辑器会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#!/usr/bin/env bash
#
# Github URL: https://github.com/vtrois/spacepack


export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

RGB_DANGER='33[31;1m'
RGB_WAIT='33[37;2m'
RGB_SUCCESS='33[32m'
RGB_WARNING='33[33;1m'
RGB_INFO='33[36;1m'
RGB_END='33[0m'

CHECK_CENTOS=$( cat /etc/redhat-release|sed -r 's/.* ([0-9]+)..*/1/' )
CHECK_RAM=$( cat /proc/meminfo | grep "MemTotal" | awk -F" " '{ram=$2/1000000}{printf("%.0f",ram)}' )

LOCK=/var/log/init_centos7_record.log

tool_info() {
echo -e "========================================================================================="
echo -e " Init CentOS 7 Script "
echo -e " For more information please visit https://github.com/vtrois/spacepack "
echo -e "========================================================================================="
}

check_root(){
if [[ $EUID -ne 0 ]]; then
echo -e "${RGB_DANGER}This script must be run as root!${RGB_END}"
exit 1
fi
}

check_lock() {
if [ ! -f "$LOCK" ];then
touch $LOCK
else
echo -e "${RGB_DANGER}Detects that the initialization is complete and does not need to be initialized any further!${RGB_END}"
exit 1
fi
}

check_os() {
if [ "${CHECK_CENTOS}" != '7' ]; then
echo -e "${CHECK_CENTOS}"
echo -e "${RGB_DANGER}This script must be run in CentOS 7!${RGB_END}"
exit 1
fi
}

new_swap() {
echo "============= swap =============" >> ${LOCK} 2>&1
if [ "${CHECK_RAM}" -le '2' ]; then
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
dd if=/dev/zero of=/swapfile bs=1024 count=1048576 >> ${LOCK} 2>&1
chmod 600 /swapfile >> ${LOCK} 2>&1
mkswap /swapfile >> ${LOCK} 2>&1
swapon /swapfile >> ${LOCK} 2>&1
echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
echo '# Swap' >> /etc/sysctl.conf
echo 'vm.swappiness = 10' >> /etc/sysctl.conf
sysctl -p >> ${LOCK} 2>&1
sysctl -n vm.swappiness >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
else
echo -e "${RGB_SUCCESS}Skip, no configuration needed${RGB_END}"
fi
}

open_bbr() {
echo "============= bbr =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
echo "# BBR" >> /etc/sysctl.conf
echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
sysctl -p >> ${LOCK} 2>&1
sysctl -n net.ipv4.tcp_congestion_control >> ${LOCK} 2>&1
lsmod | grep bbr >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

disable_software() {
echo "============= selinux firewalld =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
setenforce 0 >> ${LOCK} 2>&1
sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config
systemctl disable firewalld.service >> ${LOCK} 2>&1
systemctl stop firewalld.service >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

time_zone() {
echo "============= time zone =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
rm -rf /etc/localtime >> ${LOCK} 2>&1
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime >> ${LOCK} 2>&1
ls -ln /etc/localtime >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

custom_profile() {
echo "============= custom profile =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
cat > /etc/profile.d/centos7init.sh << EOF
PS1="[e[37;40m][[e[32;40m]u[e[37;40m]@h [e[35;40m]W[e[0m]]\\$ "
GREP_OPTIONS="--color=auto"
alias l='ls -AFhlt'
alias grep='grep --color'
alias egrep='egrep --color'
alias fgrep='fgrep --color'
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "
EOF
cat /etc/profile.d/centos7init.sh >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

adjust_ulimit() {
echo "============= adjust ulimit =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i '/^# End of file/,$d' /etc/security/limits.conf
cat >> /etc/security/limits.conf <<EOF
# End of file
* soft core unlimited
* hard core unlimited
* soft nproc 1000000
* hard nproc 1000000
* soft nofile 1000000
* hard nofile 1000000
root soft core unlimited
root hard core unlimited
root soft nproc 1000000
root hard nproc 1000000
root soft nofile 1000000
root hard nofile 1000000
EOF
cat /etc/security/limits.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

kernel_optimum() {
echo "============= kernel optimum =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
[ ! -e "/etc/sysctl.conf_bak" ] && /bin/mv /etc/sysctl.conf{,_bak}
cat > /etc/sysctl.conf << EOF
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.conf.all.promote_secondaries = 1
net.ipv4.conf.default.promote_secondaries = 1

# Controls the use of TCP syncookies
# Number of pid_max
kernel.core_uses_pid = 1
kernel.pid_max = 1000000
net.ipv4.tcp_syncookies = 1

# Controls the maximum size of a message, in bytes
# Controls the default maxmimum size of a mesage queue
# Controls the maximum shared segment size, in bytes
# Controls the maximum number of shared memory segments, in pages
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
kernel.sysrq = 1
kernel.softlockup_panic = 1
kernel.printk = 5

# TCP kernel paramater
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1

# Socket buffer
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 32768
net.core.somaxconn = 65535
net.core.optmem_max = 81920

# TCP conn
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 15

# TCP conn reuse
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 5
net.ipv4.tcp_max_tw_buckets = 7000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_synack_retries = 1

# keepalive conn
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.ip_local_port_range = 1024 65535

net.ipv6.neigh.default.gc_thresh3 = 4096
net.ipv4.neigh.default.gc_thresh3 = 4096
EOF
sysctl -p >> ${LOCK} 2>&1
cat /etc/sysctl.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}


updatedb_optimum() {
echo "============= updatedb optimum =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's,media,media /data,' /etc/updatedb.conf
cat /etc/updatedb.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

open_ipv6() {
echo "============= open ipv6 =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
echo '# IPV6' >> /etc/sysctl.conf
echo 'net.ipv6.conf.all.disable_ipv6=0' >> /etc/sysctl.conf
echo 'net.ipv6.conf.default.disable_ipv6=0' >> /etc/sysctl.conf
echo 'net.ipv6.conf.lo.disable_ipv6=0' >> /etc/sysctl.conf
sysctl -p >> ${LOCK} 2>&1
cat /etc/sysctl.conf >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

disable_cad() {
echo "============= disable cad =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
systemctl mask ctrl-alt-del.target >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

remove_users() {
echo "============= remove users =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
for u in adm lp sync shutdown halt mail operator games ftp
do
userdel ${u} >> ${LOCK} 2>&1
done
cut -d : -f 1 /etc/passwd >> ${LOCK} 2>&1
for g in adm lp mail games ftp
do
groupdel ${g} >> ${LOCK} 2>&1
done
cat /etc/group >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

sys_permissions() {
echo "============= sys permissions =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
chmod 644 /etc/passwd >> ${LOCK} 2>&1
chmod 644 /etc/group >> ${LOCK} 2>&1
chmod 000 /etc/shadow >> ${LOCK} 2>&1
chmod 000 /etc/gshadow >> ${LOCK} 2>&1
ls -la /etc/passwd >> ${LOCK} 2>&1
ls -la /etc/group >> ${LOCK} 2>&1
ls -la /etc/shadow >> ${LOCK} 2>&1
ls -la /etc/gshadow >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

password_policy() {
echo "============= password policy =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's/^PASS_MAX_DAYS.*$/PASS_MAX_DAYS 90/' /etc/login.defs
sed -i 's/^PASS_MIN_DAYS.*$/PASS_MIN_DAYS 10/' /etc/login.defs
cat /etc/login.defs >> ${LOCK} 2>&1
cat >>/etc/security/pwquality.conf << EOF
minlen = 8
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
EOF
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

change_useradd() {
echo "============= change useradd =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's/^INACTIVE.*$/INACTIVE=180/' /etc/default/useradd
cat /etc/default/useradd >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

sec_ssh() {
echo "============= sec ssh =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
sed -i 's/UseDNS.*$/UseDNS no/' /etc/ssh/sshd_config
sed -i 's/^#LoginGraceTime.*$/LoginGraceTime 60/' /etc/ssh/sshd_config
sed -i 's/^#PermitEmptyPasswords.*$/PermitEmptyPasswords no/' /etc/ssh/sshd_config
sed -i 's/^#PubkeyAuthentication.*$/PubkeyAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/^#MaxAuthTries.*$/MaxAuthTries 3/' /etc/ssh/sshd_config
sed -i "s/#ClientAliveInterval 0/ClientAliveInterval 30/g" /etc/ssh/sshd_config
sed -i "s/#ClientAliveCountMax 3/ClientAliveCountMax 3/g" /etc/ssh/sshd_config
sed -i "s/X11Forwarding yes/X11Forwarding no/g" /etc/ssh/sshd_config
sed -i "s/#Banner none/Banner /etc/issue.net/g" /etc/ssh/sshd_config
echo "Authorized users only. All activity may be monitored and reported.">/etc/issue.net
systemctl restart sshd.service >> ${LOCK} 2>&1
cat /etc/ssh/sshd_config >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

timeout_config() {
echo "============= timeout config =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
echo "export TMOUT=1800" >> /etc/profile.d/centos7init.sh
cat /etc/profile.d/centos7init.sh >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}

lockout_policy() {
echo "============= lockout policy =============" >> ${LOCK} 2>&1
echo -en "${RGB_WAIT}Configuring...${RGB_END}"
[ ! -e "/etc/pam.d/system-auth_bak" ] && /bin/mv /etc/pam.d/system-auth{,_bak}
cat > /etc/pam.d/system-auth << EOF
auth required pam_env.so
auth required pam_faillock.so preauth silent audit deny=3 unlock_time=300
auth required pam_faildelay.so delay=2000000
auth [default=1 ignore=ignore success=ok] pam_succeed_if.so uid >= 1000 quiet
auth [default=1 ignore=ignore success=ok] pam_localuser.so
auth sufficient pam_unix.so nullok try_first_pass
auth [default=die] pam_faillock.so authfail audit deny=3 unlock_time=300
auth requisite pam_succeed_if.so uid >= 1000 quiet_success
auth sufficient pam_sss.so forward_pass
auth required pam_deny.so

account required pam_unix.so
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 1000 quiet
account [default=bad success=ok user_unknown=ignore] pam_sss.so
account required pam_permit.so
account required pam_faillock.so

password requisite pam_pwquality.so try_first_pass local_users_only
password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password sufficient pam_sss.so use_authtok
password required pam_deny.so

session optional pam_keyinit.so revoke
session required pam_limits.so
-session optional pam_systemd.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so
session optional pam_sss.so
EOF
[ ! -e "/etc/pam.d/password-auth_bak" ] && /bin/mv /etc/pam.d/password-auth{,_bak}
cat > /etc/pam.d/password-auth << EOF
auth required pam_env.so
auth required pam_faillock.so preauth silent audit deny=3 unlock_time=300
auth required pam_faildelay.so delay=2000000
auth [default=1 ignore=ignore success=ok] pam_succeed_if.so uid >= 1000 quiet
auth [default=1 ignore=ignore success=ok] pam_localuser.so
auth sufficient pam_unix.so nullok try_first_pass
auth [default=die] pam_faillock.so authfail audit deny=3 unlock_time=300
auth requisite pam_succeed_if.so uid >= 1000 quiet_success
auth sufficient pam_sss.so forward_pass
auth required pam_deny.so

account required pam_unix.so
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid < 1000 quiet
account [default=bad success=ok user_unknown=ignore] pam_sss.so
account required pam_permit.so
account required pam_faillock.so

password requisite pam_pwquality.so try_first_pass local_users_only
password sufficient pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password sufficient pam_sss.so use_authtok
password required pam_deny.so

session optional pam_keyinit.so revoke
session required pam_limits.so
-session optional pam_systemd.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required pam_unix.so
session optional pam_sss.so
EOF
systemctl restart sshd.service >> ${LOCK} 2>&1
cat /etc/pam.d/etc/pam.d/system-auth >> ${LOCK} 2>&1
cat /etc/pam.d/password-auth >> ${LOCK} 2>&1
echo -e "
${RGB_SUCCESS}Configuration Success${RGB_END}"
}


reboot_os() {
echo -e "
${RGB_WARNING}Please restart the server and see if the services start up fine.${RGB_END}"
echo -en "${RGB_WARNING}Do you want to restart OS ? [y/n]: ${RGB_END}"
while :; do
read REBOOT_STATUS
if [[ ! "${REBOOT_STATUS}" =~ ^[y,n]$ ]]; then
echo -en "${RGB_DANGER}Input error, please only input 'y' or 'n': ${RGB_END}"
else
break
fi
done
[ "${REBOOT_STATUS}" == 'y' ] && reboot
}

main() {
echo -e "
${RGB_INFO}1/18 : Start Init CentOS7 Script ${RGB_END}"

echo -e "
${RGB_INFO}2/18 : Customize the profile (color and alias)${RGB_END}"
custom_profile

echo -e "
${RGB_INFO}3/18 : Time zone adjustment${RGB_END}"
time_zone

echo -e "
${RGB_INFO}4/18 : Disable selinux and firewalld${RGB_END}"
disable_software

echo -e "
${RGB_INFO}5/18 : Disable Ctrl+Alt+Del${RGB_END}"
disable_cad

echo -e "
${RGB_INFO}6/18 : Kernel parameter optimization${RGB_END}"
kernel_optimum

echo -e "
${RGB_INFO}7/18 : The updatedb optimization${RGB_END}"
updatedb_optimum

echo -e "
${RGB_INFO}8/18 : Adding swap space${RGB_END}"
new_swap

echo -e "
${RGB_INFO}9/18 : Adjustment of ulimit${RGB_END}"
adjust_ulimit

echo -e "
${RGB_INFO}10/18 : Enable tcp bbr congestion control algorithm${RGB_END}"
open_bbr

echo -e "
${RGB_INFO}11/18 : Enable IPV6${RGB_END}"
open_ipv6

echo -e "
${RGB_INFO}12/18 : Remove unnecessary users and user groups from the system${RGB_END}"
remove_users

echo -e "
${RGB_INFO}13/18 : System permissions for sensitive files${RGB_END}"
sys_permissions

echo -e "
${RGB_INFO}14/18 : Modify Account Password Survival Policy${RGB_END}"
password_policy

echo -e "
${RGB_INFO}15/18 : Maximum number of days an account is valid after password expiration strategy${RGB_END}"
change_useradd

echo -e "
${RGB_INFO}16/18 : Secure configuration of SSH${RGB_END}"
sec_ssh

echo -e "
${RGB_INFO}17/18 : Timeout Auto-Logout Configuration${RGB_END}"
timeout_config

echo -e "
${RGB_INFO}18/18 : Configure account login failure lockout policy${RGB_END}"
lockout_policy


reboot_os
}

clear
tool_info
check_root
check_os
check_lock
main

一辈子很短,努力的做好两件事就好;
第一件事是热爱生活,好好的去爱身边的人;
第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;

继开 wechat
欢迎加我的微信,共同交流技术